import React, { useEffect, useRef, useState } from "react";
import { Button, Form, Input, Space, DatePicker, Select } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import TheButton from "@/components/TheButton";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheImage from "@/components/TheImage";
import { apiGetAdoptClassifyList, apiGetAdoptPage, apiGetAdoptDel } from '@/request/adopt'
import { getDateTime3 } from '@/utils/getDate'
import _ from 'lodash'
const { RangePicker } = DatePicker;

const SearchHeader = ({ goAdd, setValue }) => {
  const formRef = useRef()
  const [options, setOptions] = useState([])
  useEffect(async () => {
    let res = await apiGetAdoptClassifyList({ status: '1' })
    if (res.data && res.code === 0) {
      let options = res.data
      options = options.map(v => {
        return {
          label: v.petAdoptionVarietyName,
          value: v.petAdoptionVarietyId
        }
      })
      setOptions(options)
    }
  }, [])
  const onFinish = values => {
    if (values.time && values.time.length) {
      values.createStartTime = getDateTime3(values.time[0]) + ' 00:00:00'
      values.createEndTime = getDateTime3(values.time[1]) + ' 23:59:59'
    }
    delete (values.time)
    _.forIn(values, (v, k) => {
      if (!v) {
        delete (values[k])
      }
    })
    setValue(values)
  }
  const reset = () => {
    formRef.current.setFieldsValue({
      petAdoptionId: '',
      petName: '',
      time: [],
      petAdoptionVarietyId: null,
      petAdoptionStatus: null
    })
    setValue({})
  }
  return (
    <div
      className="p-search-box"
      style={{ display: "flex", justifyContent: "space-between" }}
    >
      <Form ref={formRef} layout="inline" onFinish={onFinish}>
        <Form.Item name={"petAdoptionId"}>
          <Input
            style={{ width: 140 }}
            suffix={<SearchOutlined />}
            placeholder={"请输入宠物ID"}
          />
        </Form.Item>
        <Form.Item name={"petName"}>
          <Input
            style={{ width: 160 }}
            suffix={<SearchOutlined />}
            placeholder={"请输入宠物名称"}
          />
        </Form.Item>
        <Form.Item name={"petAdoptionVarietyId"}>
          <Select style={{ width: 140 }} options={options} placeholder={"请选择宠物类型"} />
        </Form.Item>
        <Form.Item name={"petAdoptionStatus"}>
          <Select style={{ width: 140 }} options={[{ label: '已领养', value: '1' }, { label: '未领养', value: '0' }]} placeholder={"请选择领养状态"} />
        </Form.Item>
        <Form.Item name={"time"} label="创建时间">
          <RangePicker />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button htmlType="submit" type="primary">搜索</Button>
            <Button onClick={reset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>
      <TheButton haspermi={['adopt:list:add']} type="default" size="middle" onClick={goAdd}>
        添加宠物领养
      </TheButton>
    </div>
  );
};

class List extends React.Component {
  state = {
    columns: [
      {
        title: "ID",
        dataIndex: "petAdoptionId",
        key: "petAdoptionId",
      },
      {
        title: "宠物封面",
        dataIndex: "petShowFile",
        key: "petShowFile",
        render: (text, record) => {
          return <TheImage src={record.petShowFile} width={80} height={80} />
        }
      },
      {
        title: "宠物昵称",
        dataIndex: "petName",
        key: "petName",
        render: (text, record) => {
          return <div className="p-white-space" style={{ width: 200 }}>{record.petName}</div>
        }
      },
      {
        title: "宠物性别",
        dataIndex: "petSex",
        key: "petSex",
        render: (text, record) => {
          let label = ''
          switch (record.petSex) {
            case '1':
              label = '雄'
              break;
            case '2':
              label = '雌'
              break;
            default:
              label = '未知性别'
          }
          return label;
        }
      },
      {
        title: "宠物年龄",
        dataIndex: "petAge",
        key: "petAge",
      },
      {
        title: "宠物类别",
        dataIndex: "petAdoptionVarietyName",
        key: "petAdoptionVarietyName",
      },
      {
        title: "领养状态",
        dataIndex: "status",
        key: "status",
        render: (text, record) => {
          let label = ''
          switch (record.status) {
            case '1':
              label = '已领养'
              break;
            case '0':
              label = '未领养'
              break;
            default:
              label = '未知领养状态'
          }
          return label;
        }
      },
      {
        title: "创建时间",
        dataIndex: "createTime",
        key: "createTime",
      },
      {
        title: "操作",
        fixed: "right",
        render: (text, render) => {
          return (
            <div>
              <TheButton haspermi={['adopt:list:record']} onClick={() => this.props.history.push(`/adopt/apply/${render.petAdoptionId}`)}>申请记录</TheButton>
              <TheButton haspermi={['adopt:list:detail']} onClick={() => this.props.history.push(`/adopt/details/${render.petAdoptionId}`)}>详情</TheButton>
              <TheButton haspermi={['adopt:list:edit']} onClick={() => this.props.history.push(`/adopt/editor/${render.petAdoptionId}`)}>编辑</TheButton>
              <TheButton  haspermi={['adopt:list:delete']}  onClick={() => this.delConfirm(render.petAdoptionId)}>删除</TheButton>
            </div>
          );
        },
      },
    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 0,
    searchValue: {}
  };
  async componentDidMount() {
    await this.getData()
  }
  getData = async () => {
    const { pageData, searchValue } = this.state
    let res = await apiGetAdoptPage({ ...pageData, ...searchValue })
    if (res.code === 0 && res.data) {
      this.setState({
        pageData: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        total: res.totalCount,
        dataSource: res.data
      })
    }
  }
  goAdd = () => {
    this.props.history.push("/adopt/add");
  };
  delConfirm = petAdoptionId => {
    React.$confirm({
      title: '您确定删除此条领养信息吗？',
      onOk: async () => {
        let res = await apiGetAdoptDel({ petAdoptionId })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '删除成功'
          })
          this.getData()
        }
      }
    })
  }
  setValue = values => {
    this.setState({
      searchValue: values,
      pageData: {
        pageNo: 1,
        pageSize: 10
      }
    }, () => this.getData())
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => this.getData())
  }
  render() {
    const {
      columns,
      dataSource,
      pageData: { pageNo, pageSize },
      total,
    } = this.state;
    return (
      <div className="p-layout-box">
        <SearchHeader goAdd={this.goAdd} setValue={this.setValue} />
        <div className="p-layout-content-pagination">
          <TheTable
            scroll={{ x: "max-content", y: '63vh' }}
            columns={columns}
            dataSource={dataSource}
          />
          <ThePagination pageNo={pageNo} pageSize={pageSize} total={total} pageChange={this.pageChange} />
        </div>
      </div>
    );
  }
}

export default List;
